package com.zbkj.admin.controller;

import cn.hutool.core.img.GraphicsUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.dtflys.forest.Forest;
import com.github.hui.quick.plugin.base.awt.GraphicUtil;
import com.github.hui.quick.plugin.image.wrapper.create.ImgCreateOptions;
import com.github.hui.quick.plugin.image.wrapper.create.ImgCreateWrapper;
import com.github.hui.quick.plugin.image.wrapper.merge.cell.ImgCell;
import com.github.hui.quick.plugin.image.wrapper.merge.cell.RectCell;
import com.github.hui.quick.plugin.qrcode.v3.constants.DrawStyle;
import com.github.hui.quick.plugin.qrcode.v3.draw.IDrawing;
import com.github.hui.quick.plugin.qrcode.wrapper.QrCodeGenV3;
import com.zbkj.admin.model.user.User;
import com.zbkj.admin.service.ProductService;
import com.zbkj.admin.service.QrCodeService;
import com.zbkj.admin.service.UserService;
import com.zbkj.admin.util.RC4Util;
import com.zbkj.admin.vo.QrCodeVo;
import jakarta.servlet.http.HttpServletResponse;
import lombok.Cleanup;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.dreamlu.mica.core.result.R;
import net.dreamlu.mica.core.utils.Base64Util;
import net.dreamlu.mica.core.utils.Charsets;
import net.dreamlu.mica.core.utils.ImageUtil;
import net.dreamlu.mica.core.utils.WebUtil;
import net.dreamlu.mica.qrcode.QrCode;
import org.apache.batik.anim.dom.SAXSVGDocumentFactory;
import org.apache.batik.anim.dom.SVGDOMImplementation;
import org.apache.batik.transcoder.*;
import org.apache.batik.transcoder.image.PNGTranscoder;
import org.apache.batik.util.XMLResourceDescriptor;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import org.w3c.dom.DOMImplementation;
import org.w3c.dom.Document;
import org.w3c.dom.bootstrap.DOMImplementationRegistry;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.Ellipse2D;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URI;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicLong;

/**
 * 二维码
 */
@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/front/qr")
public class QrController {
    private final UserService userService;
    private final QrCodeService qrCodeService;
    private final ProductService productService;

    @GetMapping("productQr")
    public R<String> productQr(@RequestParam("id") Long id, @RequestParam("mt") Long mt,
                               @RequestParam("pUid") Long pUid) {
        return R.success(QrCode.form("http://api.huikexin.fun/pages/goods/goods_details/index?id=" + id
                        + "&mt=" + mt + "&pUid=" + pUid)
                .size(512) // 默认 512，可以不设置
                .backGroundColor(Color.WHITE) // 默认白色，可以不设置
                .foreGroundColor(Color.BLACK) // 默认黑色，可以不设置
                .encode(Charsets.UTF_8) // 默认 UTF_8，可以不设置
                .imageFormat("png") // 默认 png，可以不设置
                .deleteMargin(true) // 删除白边，默认为 true，可以不设置
//                .logo("/Users/lcm/Desktop/mica-mqtt-01.png") // 设置二维码 logo，支持 URL 远程图片、文件和流
                .toBase64());
    }

    @GetMapping("qr")
    public R<String> qr() { // posterImg
        User info = userService.getInfo();
//        String input = String.valueOf(6);
//        log.debug("二维码生成用户 {}, code {}", 6, input);
        return R.success(QrCode.form("http://api.huikexin.fun/pages/userEnroll/index?code=" + info.getId())
                .size(512) // 默认 512，可以不设置
                .backGroundColor(Color.WHITE) // 默认白色，可以不设置
                .foreGroundColor(Color.BLACK) // 默认黑色，可以不设置
                .encode(Charsets.UTF_8) // 默认 UTF_8，可以不设置
                .imageFormat("png") // 默认 png，可以不设置
                .deleteMargin(true) // 删除白边，默认为 true，可以不设置
//                .logo("/Users/lcm/Desktop/mica-mqtt-01.png") // 设置二维码 logo，支持 URL 远程图片、文件和流
                .toBase64()); // 写出，同类方法有 toImage、toStream、toBytes)
    }

    @GetMapping("/posterImgDown")
    @SuppressWarnings("all")
    public void posterImgDown(
            @RequestParam(value = "avatar", required = false) String avatar,
            @RequestParam(value = "nickname", required = false) String nickname,
            @RequestParam(value = "text", required = false) List<String> text
    ) throws Exception {
        HttpServletResponse response = WebUtil.getResponse();
        ByteArrayOutputStream byteArrayOutputStream = createImg(avatar, nickname, text);
        response.setCharacterEncoding("UTF-8");
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(IdUtil.nanoId()
                + ".png", "UTF-8"));
        response.setContentType("image/png;charset=utf-8");
        response.addHeader("Content-Length", "" + byteArrayOutputStream.size());
        OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
        outputStream.write(byteArrayOutputStream.toByteArray());
        outputStream.flush();
    }

    @GetMapping("/posterImg")
    public R<String> posterImg(
            @RequestParam(value = "avatar", required = false) String avatar,
            @RequestParam(value = "nickname", required = false) String nickname,
            @RequestParam(value = "text", required = false) List<String> text
    ) {
        ByteArrayOutputStream byteArrayOutputStream = createImg(avatar, nickname, text);
        return R.success("data:image/png;base64," + Base64Util.encodeToString(byteArrayOutputStream.toByteArray()));
    }


    private ByteArrayOutputStream createImg(String avatar, String nickname, List<String> text) {
        User info = userService.getInfo();
//        ImgCell cell = new ImgCell();
        String format = StrUtil.format("sd={}&icode={}", info.getId(), RC4Util.encrypt( info.getId().longValue()));
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("scene", format);
        jsonObject.put("page", "pages/index/index");
        jsonObject.put("width", 400);
//        jsonObject.put("height", 430);
        jsonObject.put("auto_color", false);
        jsonObject.put("line_color", Dict.of().set("r", "0").set("g", "0").set("b", "0"));
        jsonObject.put("is_hyaline", true);
        QrCodeVo wecahtQrCode = qrCodeService.getWecahtQrCode(jsonObject);
        ClassPathResource br = new ClassPathResource("/images/bottomPoster.png", getClass());
        // 从classpath/resources目录加载字体
        ClassPathResource fontResource = new ClassPathResource("/font/msyh.ttc",  getClass());
        Font customFont = null;
        try {
            customFont = Font.createFont(Font.TRUETYPE_FONT, fontResource.getInputStream());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
        ge.registerFont(customFont);

        ImgCreateWrapper.Builder build = ImgCreateWrapper.build()
                .setImgW(293) // 设置图片宽
                .setAlignStyle(ImgCreateOptions.AlignStyle.CENTER) // 文字对齐方式
                .setDrawStyle(ImgCreateOptions.DrawStyle.HORIZONTAL) // 绘制样式，水平绘制
                .setBgColor(Color.WHITE) // 背景色为白色
                .setBorder(false); // 输出图片有边框
        if (Objects.isNull(wecahtQrCode)) {
            throw new RuntimeException("微信二维码生成失败");
        }
        // 1. 移除Base64前缀（如果存在，如"data:image/png;base64,"）
        String base64Data = wecahtQrCode.getCode().split(",")[wecahtQrCode.getCode().split(",").length > 1 ? 1 : 0];

        // 2. 解码Base64字符串为字节数组
        byte[] imageBytes = Base64.getDecoder().decode(base64Data);
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        try (ByteArrayInputStream bis = new ByteArrayInputStream(imageBytes)) {
            build.drawImage(ImageIO.read(br.getInputStream()));
            BufferedImage imageWx = ImageIO.read(bis), ftImg = GraphicUtil.createImg(500, 600, imageWx), brImg = ImageIO.read(br.getInputStream());
            BufferedImage image = GraphicUtil.createImg(brImg.getWidth(), brImg.getHeight(), brImg);
            ImgCell cell = new ImgCell();
            Graphics2D graphics2D = GraphicUtil.getG2d(image);
//            graphics2D.setColor(Color.WHITE);
//            graphics2D.fillRect(280, brImg.getHeight() - 300, 450, 450);
            graphics2D.setColor(Color.BLACK);
            graphics2D.setFont(new Font("Microsoft YaHei", Font.BOLD, 36));
            AtomicLong x_index = new AtomicLong(210);
            AtomicLong y_index = new AtomicLong(830);
            for (int i = 0; i < text.size(); i++) {
                if (i == 0) {
                    graphics2D.drawString(text.get(i), x_index.get(), y_index.get());
                } else {
                    long xindex = i == 1 ? x_index.updateAndGet(current -> current - 30) : x_index.get();
                    graphics2D.drawString(text.get(i), xindex, y_index.addAndGet(40));
                }
            }
            cell.setImg(ftImg);
            cell.setX(125);
            cell.setY(460);
            cell.setW(450);
            cell.setH(470);
            cell.draw(graphics2D);
            graphics2D.dispose();
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(Forest
                    .get(avatar).executeAsByteArray());
            BufferedImage bufferedImage = ImageIO.read(byteArrayInputStream);
            Graphics2D head = GraphicUtil.getG2d(image);
            head.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            // 定义圆形的位置和尺寸
            int diameter = Math.min(bufferedImage.getWidth(), bufferedImage.getHeight()) - 20; // 直径取面板宽高的较小值减20
            int x = 100;
            int y = 950;

            // 1. 创建圆形剪切区域
            Ellipse2D circle = new Ellipse2D.Double(x, y, diameter, diameter);
            head.setClip(circle);
            // 2. 绘制图片（自动缩放并居中）
            if (bufferedImage != null) {
                // 计算图片缩放比例
                double scale = Math.min((double) diameter / bufferedImage.getWidth(),
                        (double) diameter / bufferedImage.getHeight());
                int scaledWidth = (int) (bufferedImage.getWidth() * scale);
                int scaledHeight = (int) (bufferedImage.getHeight() * scale);

//                // 计算图片绘制位置（居中）
                int imgX = x + (diameter - scaledWidth) / 2;
                int imgY = y + (diameter - scaledHeight) / 2;

                // 绘制缩放后的图片
                head.drawImage(bufferedImage, imgX, imgY, scaledWidth, scaledHeight, null);
            }

            // 3. 绘制圆形边框（可选）
            head.setClip(null); // 清除剪切区域
            head.setStroke(new BasicStroke(6)); // 边框粗细
            head.setColor(Color.WHITE);         // 边框颜色
            head.draw(circle);
            head.dispose(); // 释放Graphics2D资源
            Graphics2D graphics2D1 = GraphicUtil.getG2d(image);
            graphics2D1.setColor(Color.BLACK);
            graphics2D1.setFont(new Font("Microsoft YaHei", Font.BOLD, 36));
            graphics2D1.drawString(nickname, 235, 1020);
            graphics2D1.dispose();
            try {
                ImageIO.write(image, "png", byteArrayOutputStream);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return byteArrayOutputStream;
//        ImgCreateWrapper.Builder build = ImgCreateWrapper.build()
//                .setImgW(293) // 设置图片宽
//                .setAlignStyle(ImgCreateOptions.AlignStyle.CENTER) // 文字对齐方式
//                .setDrawStyle(ImgCreateOptions.DrawStyle.HORIZONTAL) // 绘制样式，水平绘制
//                .setBgColor(Color.WHITE) // 背景色为白色
//                .setBorder(false); // 输出图片有边框
//        build.drawImage()
//        ClassPathResource resource = new ClassPathResource("/images/shareIcon.png", getClass());
//        ClassPathResource qr = new ClassPathResource("/images/Qr.txt", getClass());
        /*String string = null;
        try {
            string = IoUtil.readUtf8(qr.getInputStream());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        try {
            build.drawImage(ImageUtil.read(resource.getInputStream()));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
//        build.drawImage("http://8.134.79.41:9000/app/shareIcon.png");
        BufferedImage image = build.asImage();

        ImgCell cell = new ImgCell();
//        cell.setImg(QrCode.form("http://api.huikexin.fun/pages/userEnroll/index?code=" + RC4Util.encrypt("" + info.getId()))
//                .size(67) // 默认 512，可以不设置
//                .backGroundColor(Color.WHITE) // 默认白色，可以不设置
//                .foreGroundColor(Color.BLACK) // 默认黑色，可以不设置
//                .encode(Charsets.UTF_8) // 默认 UTF_8，可以不设置
//                .imageFormat("png") // 默认 png，可以不设置
//                .deleteMargin(true) // 删除白边，默认为 true，可以不设置
////                .logo("/Users/lcm/Desktop/mica-mqtt-01.png") // 设置二维码 logo，支持 URL 远程图片、文件和流
//                .toImage());
        try {
//            ImageUtil.read(new ByteArrayOutputStream().toByteArray())
            String img1 = QrCodeGenV3.of("http://api.huikexin.fun/pages/userEnroll/index?code="
//                            + RC4Util.encrypt("" + info.getId())
                    )
                    .setW(400).setSvgTemplate(string).build().asSvg();
//            String img = (String) img1
            BufferedImage bufferedImage = convertSVGToBufferedImage(img1);
            Graphics2D g2d = bufferedImage.createGraphics();
            try {
                g2d.setColor(Color.WHITE);
//                g2d.setComposite(AlphaComposite.Src); // 覆盖原有内容
                g2d.fillRect(0, 0, bufferedImage.getWidth(), bufferedImage.getHeight());
            } finally {
                g2d.dispose();
            }
//            cell.setImg(image);
            String format = StrUtil.format("sd={}&icode={}", info.getId(), RC4Util.encrypt("" + info.getId()));
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("scene", format);
            jsonObject.put("page", "pages/index/index");
            jsonObject.put("width", 400);
            jsonObject.put("auto_color", false);
            jsonObject.put("line_color", Dict.of().set("r","0").set("g","0").set("b","0"));
            jsonObject.put("is_hyaline", true);
            QrCodeVo wecahtQrCode = qrCodeService.getWecahtQrCode(jsonObject);
            if (Objects.isNull(wecahtQrCode)) {
                throw new RuntimeException("微信二维码生成失败");
            }
            // 1. 移除Base64前缀（如果存在，如"data:image/png;base64,"）
            String base64Data = wecahtQrCode.getCode().split(",")[wecahtQrCode.getCode().split(",").length > 1 ? 1 : 0];

            // 2. 解码Base64字符串为字节数组
            byte[] imageBytes = Base64.getDecoder().decode(base64Data);

            // 3. 将字节数组转换为BufferedImage
            try (ByteArrayInputStream bis = new ByteArrayInputStream(imageBytes)) {
                BufferedImage imageWx = ImageIO.read(bis);
                cell.setImg(imageWx);
                if (image == null) {
                    throw new IOException("Failed to decode image: Invalid format or corrupted data.");
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        cell.setX(70);
        cell.setY(250);
        cell.setW(150);
        cell.setH(150);
        cell.draw(GraphicUtil.getG2d(image));
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        try {
            ImageIO.write(image, "png", byteArrayOutputStream);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return byteArrayOutputStream;*/
    }


//    public BufferedImage convertSVGToBufferedImage(String svg) throws IOException, TranscoderException {
//        try {
//            // 1. 创建 SVG 文档工厂
//            SAXSVGDocumentFactory factory = new SAXSVGDocumentFactory(XMLResourceDescriptor.getXMLParserClassName());
//
//            // 2. 加载 SVG 文档（显式指定字符编码）
//            Document document = factory.createDocument(null, new StringReader(svg));
//
//            // 3. 配置 PNG 转码器
//            PNGTranscoder transcoder = new PNGTranscoder();
//            TranscodingHints hints = new TranscodingHints();
//            hints.put(PNGTranscoder.KEY_BACKGROUND_COLOR, Color.WHITE);
//            hints.put(PNGTranscoder.KEY_FORCE_TRANSPARENT_WHITE, Boolean.FALSE);
//
//            // 应用用户样式表（优化 base64 编码）
//            String css = "svg { background: white !important; }";
//            String encodedCSS = "data:text/css;base64," + Base64.getEncoder().encodeToString(css.getBytes(StandardCharsets.UTF_8));
//            hints.put(PNGTranscoder.KEY_USER_STYLESHEET_URI, encodedCSS);
//            transcoder.setTranscodingHints(hints);
//
//            // 4. 执行转换
//            try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
//                transcoder.transcode(new TranscoderInput(document), new TranscoderOutput(outputStream));
//                return ImageIO.read(new ByteArrayInputStream(outputStream.toByteArray()));
//            }
//        } catch (IOException | TranscoderException e) {
//            throw e;  // 重新抛出具体异常
//        } catch (Exception e) {
//            throw new TranscoderException("Unexpected error during SVG conversion", e);
//        }
//    }


    @GetMapping("/poster")
    public ModelAndView poster() {
        return new ModelAndView("poster");
    }

}
